package org.zhxy.config.mvc;

import cn.hutool.core.convert.Convert;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zhxy.model.constant.JWTConstant;
import org.zhxy.model.context.LoginContextHolder;
import org.zhxy.model.entity.Admin;
import org.zhxy.model.exception.BizException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 token
        String token = request.getHeader("token");
        if (token == null) {
            throw new BizException("token 失效，请重新登录");
        }
        // 校验 token
        boolean verify = JWTUtil.verify(token, JWTConstant.SECRET.getBytes());
        if (!verify) {
            throw new BizException("token 失效，请重新登录");
        }
        // 解析 token
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = Convert.toInt(jwt.getPayload(JWTConstant.USER_ID));
        Integer userType = Convert.toInt(jwt.getPayload(JWTConstant.USER_TYPE));
        // 保存到 Holder
        LoginContextHolder.setUserId(userId);
        LoginContextHolder.setUserType(userType);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.clear();
    }
}
